package com.loveto.service;

import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class SetupAlarmActivity extends BaseActivity implements
View.OnClickListener {
	
	// 사용하는 변수들
	private ProgressDialog progressDialog;
	private Handler myHandler = new Handler();
	private String memberid;
	private String message_notify_yn;
	private String tournament_notify_yn;
	private String following_notify_yn;
	private boolean isSaveSuccess;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_setup_alarm);
		
		//변수 초기화
		progressDialog = new ProgressDialog(this);
		message_notify_yn = "N";
		tournament_notify_yn = "N";
		following_notify_yn = "N";
		isSaveSuccess = false;
		
		//유저정보 받아오기
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "김기용");
		
		//클릭 리스너 달기
		((RelativeLayout)findViewById(R.id.btn_goto_back)).setOnClickListener(this);
		((TextView)findViewById(R.id.btn_save_info)).setOnClickListener(this);
		
		if (isNetworkAvailableAndNotice()) {
			getAlarmInfo();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_save_info:
				setAlarmInfo();
				break;
			case R.id.btn_goto_back:
				finish();
				break;
		}
	}
	
	private void getAlarmInfo() {
		progressDialog.setMessage("정보를 불러오고 있습니다.");
		progressDialog.show();
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
							Log.d("tag", "getAlarmInfo start");
							
							try {
								//서버에 정보 보내기
								String jsonText = JsonUtils.getStringFromUrl(LovetoConstant.SETUP_ALARM_GET + "?memberid=" + memberid);
								Log.d("tag", "jsonText : " + jsonText);
								//JSONArray jsonArray = new JSONArray(jsonText);
								JSONObject object = new JSONObject(jsonText);
								
								String message_notify_yn = object.getString("message_notify_yn");
								String tournament_notify_yn = object.getString("tournament_notify_yn");
								String following_notify_yn = object.getString("following_notify_yn");
								Log.d("tag", "message_notify_yn : " + message_notify_yn);
								Log.d("tag", "tournament_notify_yn : " + tournament_notify_yn);
								Log.d("tag", "following_notify_yn : " + following_notify_yn);
								
								//체크박스에 체크해주기
								if ("Y".equals(message_notify_yn)) { 
									Log.d("tag", "1번 바꿔");
									((CheckBox)findViewById(R.id.check_message_notify_yn)).setChecked(true);
								}
								if ("Y".equals(tournament_notify_yn)) {
									Log.d("tag", "2번 바꿔");
									((CheckBox)findViewById(R.id.check_tournament_notify_yn)).setChecked(true);
								}
								if ("Y".equals(following_notify_yn)) {
									Log.d("tag", "3번 바꿔");
									((CheckBox)findViewById(R.id.check_following_notify_yn)).setChecked(true);
								}
								
							} catch (JSONException e) {
								e.printStackTrace();
								Log.d("tag", "setRoundInfo() error, " + e.getMessage());
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
								Log.d("tag", "setRoundInfo() error, " + e.getMessage());
							} finally {
							}
							progressDialog.dismiss();
							Log.d("tag", "getAlarmInfo end");
							
						} //Handler run End
				});
			}
		};
		new Thread(runnable).start();
	}
	
	private void setAlarmInfo() {
		progressDialog.setMessage("정보를 저장하고 있습니다.");
		progressDialog.show();
		
		//알림 체크여부 가져오기
		if (((CheckBox)findViewById(R.id.check_message_notify_yn)).isChecked()) {
			message_notify_yn = "Y";
		}
		if (((CheckBox)findViewById(R.id.check_tournament_notify_yn)).isChecked()) { 
			tournament_notify_yn = "Y";
		}
		if (((CheckBox)findViewById(R.id.check_following_notify_yn)).isChecked()) {
			following_notify_yn = "Y";
		}
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						Log.d("tag", "setAlarmInfo start");
						
						try {
							//서버에 정보 보내기
							StringBuffer sb = new StringBuffer(LovetoConstant.SETUP_ALARM_SET);
							sb.append("?memberid=").append(memberid);
							sb.append("&message_notify_yn=").append(message_notify_yn);
							sb.append("&tournament_notify_yn=").append(tournament_notify_yn);
							sb.append("&following_notify_yn=").append(following_notify_yn);
							Log.d("tag", "url : " + sb.toString());
							String jsonText = JsonUtils.getStringFromUrl(sb.toString());
							Log.d("tag", "jsonText : " + jsonText);
							//JSONArray jsonArray = new JSONArray(jsonText);
							JSONObject object = new JSONObject(jsonText);
							String result = object.getString("result");
							String err = object.getString("err");
							Log.d("tag", "result : " + result);
							Log.d("tag", "err : " + err);
							if ("T".equals(result)) {
								isSaveSuccess = true;
							}
						} catch (JSONException e) {
							e.printStackTrace();
							Log.d("tag", "setRoundInfo() error, " + e.getMessage());
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
							Log.d("tag", "setRoundInfo() error, " + e.getMessage());
						} finally {
							progressDialog.dismiss();
							Log.d("tag", "setAlarmInfo end");
							if (isSaveSuccess) {
								showAlertSuccess("정보가 저장되었습니다.");
							} else {
								showAlertSuccess("실패했습니다. 다시 시도해주세요.");
							}
						}
					} //Handler run End
				});
			}
		};
		new Thread(runnable).start();
	}
	
    private void showAlertSuccess(String ment) {
    	new AlertDialog.Builder(this)
    	.setMessage(ment)
    	.setPositiveButton("확인", new DialogInterface.OnClickListener()
    	{
    		@Override
    		public void onClick(DialogInterface dialog, int which)
    		{
    			dialog.dismiss();
    			if (isSaveSuccess) {
    				finish();
    			}
    		}
    	})
    	.show();
    }

}
